import {  HttpKit } from '../axios/index'
import {  Utils } from './utils'

export class Request {
    private publicKey: string;
    private privateKey: string;
    private serverUrl: string;

    constructor(publicKey: string, privateKey: string, serverUrl: string) {
        this.privateKey = privateKey;
        this.publicKey = publicKey;
        this.serverUrl = serverUrl;
    }

    /**
     * get 方法
     * @param url           请求 url
     * @param authorization 授权信息
     * @param serialNumber  证书序列号
     */
    public static async get(url: string, authorization: string, serialNumber: string) {
        return await HttpKit.getHttpDelegate.httpGetToResponse(url, {
            headers: Utils.getHeaders(authorization, serialNumber)
        })
    }

    /**
     * post 方法
     * @param url           请求 url
     * @param authorization 授权信息
     * @param serialNumber  证书序列号
     */
    public static async post(url: string, data: string, authorization: string, serialNumber: string) {
        return await HttpKit.getHttpDelegate.httpPostToResponse(url, data, {
            headers: Utils.getHeaders(authorization, serialNumber)
        })
    }
    /**
     * 微信支付 Api-v3 get 请求
     * @param urlPrefix     请求接口前缀
     * @param urlSuffix     请求接口后缀
     * @param mchId         商户号
     * @param serialNo      证书序列号
     * @param key           key.pem 证书
     * @param params        请求参数
     * @param platSerialNo  微信平台序列号
     */
    public static async exeGet(
        urlPrefix: string,
        urlSuffix: string,
        mchId: string,
        serialNo: string,
        key: string,
        params?: Map<string, string>,
        platSerialNo?: string
    ): Promise<any> {
        if (params && params.size > 0) {
            urlSuffix = urlSuffix.concat('?').concat(Utils.createLinkString(params, '&', true, false))
        }
        let authorization = await Utils.buildAuthorization('GET', urlSuffix, mchId, serialNo, key, '');
        return await this.get(urlPrefix.concat(urlSuffix), authorization, platSerialNo || serialNo)
    }

    /**
     * 微信支付 Api-v3 post 请求
     * @param urlPrefix     请求接口前缀
     * @param urlSuffix     请求接口后缀
     * @param mchId         商户号
     * @param serialNo      证书序列号
     * @param key           key.pem 证书
     * @param data          接口请求参数
     * @param platSerialNo  微信平台序列号
     */
    public static async exePost(urlPrefix: string, urlSuffix: string, mchId: string, serialNo: string, key: string, data: string, platSerialNo?: string): Promise<any> {
        let authorization = await Utils.buildAuthorization('POST', urlSuffix, mchId, serialNo, key, data);
        return await this.post(urlPrefix.concat(urlSuffix), data, authorization, platSerialNo || serialNo)
    }

}
